package com.sdy.web;

import com.alibaba.fastjson.JSONObject;
import com.sdy.po.*;
import com.sdy.service.MenuService;
import com.sdy.service.OverViewService;
import com.sdy.service.SerialService;
import com.sdy.service.UserService;
import com.sdy.util.Contact;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统管理菜单的Controller
 * 用于接收来自系统菜单的servlet
 */

@Controller
@RequestMapping("/management")
public class ManagementSystemController {

    @Resource
    OverViewService overViewService;
    @Resource
    MenuService menuService;
    @Autowired
    UserService userService;
    @Autowired
    SerialService serialService;


    @RequestMapping("")
    public String index(){
        System.out.println("进入登陆页面");
        return "login";
    }

    /**
     * 选择公司后跳转界面
     * @param url
     * @param companyId
     * @param session
     * @return
     */
    @RequestMapping("/toPage")
    public String toContactCompanyPage(String url,Integer companyId,HttpSession session){
        session.setAttribute("contactCompany",new Company(companyId));
        session.setAttribute("CCI_"+url+"_pass",true);
        return "redirect:" + url + "?url="+url;
    }

    @RequestMapping("/batch")
    public String batchOperation(String url){
        return "";
    }

    /**
     * 串口信息模块
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("setUpSerials")
    public String setUpSerials(HttpSession session, Model model){

        Company contactCompany = (Company) session.getAttribute("contactCompany");

        //串口信息
        List<SerialPO> serialList = serialService.findByComandId(contactCompany.getId());

        model.addAttribute("Serials",serialList);

        return "pages/setUpSerials";
    }

    /**
     * 跳转至管理系统主页
     * @return
     */
    @RequestMapping("/overView")
    public String index(Model model, HttpSession session){
        //十天前
        Date startDate = new Date(new Date().getTime() - 9 * 24 * 60 * 60 * 1000);
        System.out.println(startDate);
        //获得菜单栏
        User user = (User)session.getAttribute(Contact.LOGIN_KEY);
        model.addAttribute("loginUser",user);
        List<Menu> menuList = menuService.findMenuByAuthority(user.getAuthority());
        System.out.println(menuList);
        model.addAttribute("menuList",menuList);
        //获取总览的表名
//       //获取总览的表数据
//        model.addAttribute("overViewMap",overViewService.findOverViewByDate(1,startDate,10));

        System.out.println("进入管理系统");
        return "index";
    }

    /**
     * 登陆方法
     * @param loginUN
     * @param loginPW
     * @return  返回用户信息
     */
    @RequestMapping("/doLogin")
    public String doLogin(String loginUN, String loginPW, HttpServletRequest request, Model model){
        User user = userService.doLogin(loginUN,loginPW);
        System.out.println(user.toString());
        if (user != null){
            model.addAttribute(Contact.LOGIN_KEY,user);
            request.getSession().setAttribute(Contact.LOGIN_KEY,user);
            return "redirect:/management/overView";
        }
        return "login";
    }

    /**
     * 按照日期查询天数
     * @param id
     * @param startDate
     * @param after
     * @return
     */
    @ResponseBody
    @RequestMapping("/getInformation")
    public Map<String,Object> getOverViewImformation(Integer id,@DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, Integer after){
        return overViewService.findOverViewByDate(id,startDate,after);
    }


    /**
     * 按照日期手动上传数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateParmsByDate")
    public JSONObject updateParmsByDate( @RequestParam(value = "id") Integer id,
                                         @RequestParam(value = "updateTime") String updateTime,
                                         @RequestParam(value = "sulfurDioxide") Double sulfurDioxide,  //二氧化硫
                                         @RequestParam(value = "nitrogenOxide") Double nitrogenOxide,  //氮氧化物
                                         @RequestParam(value = "particulate") Double particulate,    //颗粒物
                                         @RequestParam(value = "temperature") Double temperature,    //温度
                                         @RequestParam(value = "humidity") Double humidity,       //湿度
                                         @RequestParam(value = "flow") Double flow,           //流量
                                         @RequestParam(value = "oxygenContent") Double oxygenContent,
                                         @RequestParam(value = "data") Boolean set ){
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(updateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        OverView overView = new OverView(id,date,sulfurDioxide,nitrogenOxide,particulate,temperature,humidity,flow,oxygenContent);
        System.out.println(overView);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",overViewService.addOverView(overView, set));
        return jsonObject;
    }

    /**
     * 设备运行状态模块
     * @param model
     * @return
     */
    @RequestMapping("/statement")
    public String statement(Model model){
        //十天前
        Date startDate = new Date(new Date().getTime() - 9 * 24 * 60 * 60 * 1000);
        //获取总览的表名
        model.addAttribute("overViewNameList",overViewService.findAllOverViewName());
        //获取总览的表数据
        model.addAttribute("overViewMap",overViewService.findOverViewByDate(1,startDate,10));
        return "pages/statement";
    }

    /**
     * 更新数据模块
     * @param model
     * @return
     */
    @RequestMapping("/updateParms")
    public String updateParms(Model model){
        model.addAttribute("overViewNameList",overViewService.findAllOverViewName());
        return "pages/updateParms";
    }

    /**
     * 管理菜单模块
     * @param model
     * @return
     */
    @RequestMapping("/updateMenu")
    public String updateMenu(Model model){
        List<Menu> menus = menuService.findAllMenu();
        model.addAttribute("menus",menus);
        return "pages/updateMenu";
    }

//    /**
//     * 开始监听串口信息
//     * @param model
//     * @param session
//     * @return
//     */
//    @RequestMapping("/realStatement")
//    public String realStatement(Model model, HttpSession session){
//        System.out.println("开始接收串口数据");
//
//        // 实例化串口操作类对象
//        SerialPortUtils serialPort = new SerialPortUtils();
//        // 创建串口必要参数接收类并赋值，赋值串口号，波特率，校验位，数据位，停止位
//        ParamConfig paramConfig = new ParamConfig("COM3", 9600, 0, 8, 1);
//        // 初始化设置,打开串口，开始监听读取串口数据
//        serialPort.init(paramConfig);
//
//        session.setAttribute("serialPort",serialPort);
//        model.addAttribute("serialPort",serialPort);
//
//        return "pages/realStatement";
//    }
//
//    /**
//     * 停止监听串口信息
//     * @param request
//     */
//    @RequestMapping("/stopListenSerial")
//    @ResponseBody
//    public void stopListenSerial(HttpServletRequest request){
//        System.out.println("进入conreoller了");
//        HttpSession session = request.getSession();
//        SerialPortUtils serialPort = (SerialPortUtils) session.getAttribute("serialPort");
//        serialPort.closeSerialPort();
//    }

    @RequestMapping("/file")
    @ResponseBody
    public String file(MultipartFile whitePicture, MultipartFile blackPicture, HttpServletRequest request){
        System.out.println(request.getServletContext().getRealPath("/upload/"));
        try {
            whitePicture.transferTo(new File( "H:\\test/" + whitePicture.getOriginalFilename()));
            blackPicture.transferTo(new File( "H:\\test/" + blackPicture.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    @RequestMapping("/file")
//    @ResponseBody
//    public List<String> file(@RequestParam(value = "fileList", name = "fileList") List<MultipartFile> fileList){
//        List<String> originalFilename = new ArrayList<>();
//
//        for (MultipartFile file:fileList) {
//            originalFilename.add(file.getOriginalFilename());
//            try {
//                file.transferTo(new File( "H:\\test/" + originalFilename));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return originalFilename;
//    }

//

//    @RequestMapping("/fileUpLoad")
//    @ResponseBody
//    public void fileUpload(HttpServletRequest request){
//        System.out.println(name);
//
//        //创建一个json类型变量，用于返回数据
//        JSONObject result = new JSONObject();
//
//        for (MultipartFile file:fileList) {
//
//            //创建一个文件信息对象
//            FileInformation fileInformation = new FileInformation();
//
//            //储存上传文件用户名
//            fileInformation.setUploadUserName(name);
//
//            //获取原始文件名
//            String originalFilename = file.getOriginalFilename();
//            fileInformation.setFileName(file.getOriginalFilename());
//
//            //拼接文件保存路径
//            String dirpath = request.getServletContext().getRealPath("/upload/");
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy/MM/dd");
//            String datepath = simpleDateFormat.format(new Date());
//            String savepath = dirpath + datepath;
//
//            //创建文件保存路径，如果不存在就创建
//            File filepath = new File(savepath);
//            if (!filepath.exists()){
//                filepath.mkdirs();
//            }
//
//            //文件名的处理（上传人的名称_UUID_原名）
//            String newFileName = name + "_" + UUID.randomUUID().toString() + "_" + originalFilename;
//
//            //保存文件
//            try {
//                //储存文件
//                file.transferTo(new File(savepath +"/" + newFileName));
//                //记录储存地址
//                fileInformation.setDatepath("upload/" + datepath + "/" + newFileName);
//                //记录储存状态
//                fileInformation.setResult("成功");
//                //记录储存成功的所有文件信息
//                result.put(originalFilename,fileInformation);
////                    finalpaths[i] = "upload/" + datepath + "/" + newFileName;
////                    finalresult[i] = "成功";
//                System.out.println("文件保存成功");
//            }
//            catch (IOException e) {
//                e.printStackTrace();
//                fileInformation.setResult("失败");
//                result.put(originalFilename,fileInformation);
////                    finalresult[i] = "失败";
//                System.out.println("文件保存失败");
//            }
//        }
//        //所有文件正常保存成功
//        return result;
//
//    }

//    /**
//     * 根据权限，查询菜单模块
//     * @param status
//     * @return
//     */
//    @RequestMapping("/doGetMenu")
//    @ResponseBody
//    public JSONObject findMenuByCustomer( String status){
//        JSONObject responce = new JSONObject();
//        List<Menu> data = menuService.findMenuByCustomer(status);
//        if (data != null){
//            responce.put("data",data);
//            responce.put("result",true);
//        }
//        else {
//            responce.put("result",false);
//        }
//        return responce;
//    }
}
